package com.leetcode.August;

import java.util.Stack;

/**
 * @Description: 字符串解码
 * @Author: Mr.Fxy
 * @CreateTime: 2024-08-02 22:30
 */
public class strDecode {
    public static String decodeString(String s) {
        Stack<Integer> countStack = new Stack<>();
        Stack<StringBuilder> stringStack = new Stack<>();
        StringBuilder current = new StringBuilder();
        int k = 0;

        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                k = k * 10 + c - '0';
            } else if (c == '[') {
                countStack.push(k);
                stringStack.push(current);
                current = new StringBuilder();
                k = 0;
            } else if (c == ']') {
                StringBuilder temp = current;
                current = stringStack.pop();
                for (k = countStack.pop(); k > 0; --k) {
                    current.append(temp);
                }
            } else {
                current.append(c);
            }
        }

        return current.toString();
    }
    public static void main(String[] args) {
        String encoded = "3[a2[b]]";
        System.out.println(decodeString(encoded)); // 输出 "abababababab"
    }
}
